<?php


namespace app\Activity\controller;


use app\activity\model\ActivityItemsInActivity;
use app\activity\model\ActivityUserRecord;
use app\activity\model\Activity as ActivityModel;
use app\ApiRest;
use app\card\model\UserInfo;
use app\shop\model\IndexUser;
use app\activity\validate\ActivityValidate;
use app\shop\model\IndexUserInfo;


class WxAppActivity extends ApiRest
{
    public function listAll()
    {
        //exit;
        $param = $this->_param;
        $page_config = array(
            'page' => 1,
            'page_count' => 20
        );
        //设置页码
        if (isset($param['page']) && $param['page'] > 0) $page_config['page'] = $param['page'];
        //设置每页的数据
        if (isset($param['page_count']) && $param['page_count'] > 0) $page_config['page_count'] = $param['page_count'];
        $model = new ActivityModel();

        $filter = [
            ['a.uniacid', '=', $this->_uniacid ?? 2],
            ['a.status', '=', 1],
        ];
        if (isset($param['classify_id']) && $param['classify_id'] > 0) {
            array_push($filter, ['a.classify_id', '=', $param['classify_id']]);
        }

        if (isset($param['staff_id']) && $param['staff_id'] > 0) {

            array_push($filter, ['a.to_uid', 'in', [0, $param['staff_id']]]);

        }

        if (isset($param['keyWordForTitle']) && $param['keyWordForTitle'] != '') {
            array_push($filter, ['a.title', 'like','%'. $param['keyWordForTitle'] . '%']);
        }

//        $page_config['total'] = $model->countByFilter($filter);

        $to_uid = !empty($param['staff_id'])?$param['staff_id']:0;

        $user_info_model = new IndexUserInfo();

        $company_id = $user_info_model->getCompanyId(['fans_id'=>$to_uid],$this->_uniacid);

        $where[] = ['a.is_public','=',1];

        $where[] = ['b.company_id','=',$company_id];

//        dump($filter,$where);exit;
//        if ((isset($param['longitude']) && $param['longitude'] != 0) || (isset($param['latitude']) && $param['latitude'] != 0)) {
            $lat = !empty($param['latitude'])?$param['latitude']: 0;

            $lon = !empty($param['longitude'])?$param['longitude']: 0;

            $distance_f = "(6371 * acos (cos ( radians($lat) ) * cos( radians( a.latitude ) )  * cos( radians( a.longitude ) - radians($lon) )  
               + sin ( radians($lat) )  * sin( radians( a.latitude ) ) ) ) AS distance";

            $rsts = $model->alias('a')
                    ->join('lb_activity_activity_company b','a.id = b.atv_id','left')
                    ->where($filter)
                    ->where(function ($query) use ($where) {
                        $query->whereOr($where) ;
                    })
                    ->field('a.id, a.title, a.cover, a.start_time, a.end_time, a.sign_limit,a.sign_limit, a.sign_number, a.sign_start_time, a.sign_end_time, a.classify_id, a.longitude, a.latitude')
                    ->field($distance_f)
                    ->group('a.id desc')
                    ->order('distance asc,a.id desc')
                    ->paginate(10)
//                    ->select()
                    ->toArray();

//        } else {
//            $rsts = $model->where($filter)
//                ->field('id, title,cover, start_time, end_time, sign_limit,
//                               sign_limit, sign_number, sign_start_time, sign_end_time, classify_id, longitude, latitude')
//                ->page($page_config['page'], $page_config['page_count'])->order('id', 'desc')->select()->toArray();
//        }

        $rsts = $rsts['data'];

        if(!empty($rsts)){

            foreach ($rsts as $k => $rst) {
                $sign_start_time = $rst['sign_start_time'];
                $sign_end_time = $rst['sign_end_time'];
                $start_time = $rst['start_time'];
                $end_time = $rst['end_time'];
                $sign_limit = $rst['sign_limit'];
                $sign_number = $rst['sign_number'];
                $rsts[$k]['sign_status'] = $this->_getSignStatus($sign_start_time, $sign_end_time, $sign_limit, $sign_number);
                $rsts[$k]['type'] = $this->_getActivityStatus($start_time, $end_time, $sign_limit, $sign_number);
                $rsts[$k]['start_time'] = date('Y-m-d H:i', $rst['start_time']);
                $rsts[$k]['end_time'] = date('Y-m-d H:i', $rst['end_time']);
            }

        }


//        $page_config['total_page'] = (int)($page_config['total'] / $page_config['page_count']);
//        if (($page_config['total'] % $page_config['page_count']) > 0) $page_config['total_page'] = $page_config['total_page'] + 1;
//        //设置返回参数
//        $result = $page_config;
        //返回数据
        $rsts = transImagesOne($rsts, ['cover']);
        $result['data'] = $rsts;
        return $this->success($result);


    }

    private function _getSignStatus($sign_start_time, $sign_end_time,  $sign_limit, $sign_number)
    {
        if ($sign_number >= $sign_limit) {
            return 3;
        }
        $end_pre_day = strtotime('-1 day', strtotime(date('Y-m-d', (int)$sign_end_time)));
        $status = -1;
        if ($sign_start_time > $sign_end_time)
        {
            return $status;
        }

        $now = time();
        if ($now < $sign_start_time)
        {
            $status = 0; //未开始
        }

        if ($now >= $sign_start_time && $now < $sign_end_time)
        {
            $status = 1; //报名中
        }

        if ($now >= $sign_start_time && $now < $sign_end_time && $now >= $end_pre_day)
        {
            $status = 2; // 报名即将结束
        }

        if ($now >= $sign_end_time)
        {
            $status = 3; //报名结束
        }

        return $status;
    }

    private function _getActivityStatus($start_time, $end_time, $sign_limit, $sign_number)
    {
//        if ($sign_number >= $sign_limit)
//        {
//            return 3;
//        }
//        $end_pre_day = strtotime('-1 day', strtotime(date('Y-m-d', (int)$end_time)));
        $status = -1;
        if ($start_time > $end_time)
        {
            return $status;
        }

        $now = time();
        if ($now < $start_time)
        {
            $status = 1; //未开始
        }

        if ($now >= $start_time && $now < $end_time)
        {
            $status = 2; //活动中
        }
//
//        if ($now >= $start_time && $now < $end_time && $now >= $end_pre_day) {
//            $status = 2; // 活动即将结束
//        }

        if ($now >= $end_time)
        {
            $status = 3; //报名结束
        }

        return $status;
    }

    public function createOne()
    {
        $validate = new ActivityValidate();
        $check = $validate->scene('create')->check($this->_input);
        if ($check == false)
        {
            return $this->error($validate->getError());
        }

        $input = $this->_input;
        if (isset($input['start_time']) || isset($input['end_time']) || isset($input['sign_start_time'])|| isset($input['sign_end_time']))
        {
            if ($input['start_time']  >= $input['end_time'])
            {
                return $this->error('开始时间必须小于结束时间');
            }

            if ($input['sign_start_time']  >= $input['sign_end_time'])
            {
                return $this->error('报名开始时间必须小于报名结束时间');
            }

            if ($input['sign_start_time']   >= $input['start_time'])
            {
                return $this->error('报名开始时间必须小于活动开始时间');
            }

            if ($input['sign_end_time']   > $input['end_time'])
            {
                return $this->error('报名结束时间必须小于活动结束时间');
            }
        }
        $input['to_uid'] = $this->_user_id;
        $input['uniacid'] = $this->_uniacid;
        $model = new ActivityModel();
        $activity_id = $model->createOne($input);

        if (!$activity_id)
        {
            return $this->error('fail');
        }

        $arcitity_item_ids = explode(',', $this->_input['items'] ?? '');
        $items_model = new \app\activity\model\ActivityItem();
        $acticity_items_data = $items_model->getAllByIds($arcitity_item_ids);

        $time = time();
        $saveData = [];
        foreach ($acticity_items_data as $data) {
            $saveData[] = [
                'create_time' => $time,
                'update_time' => $time,
                'activity_id' => $activity_id,
                'uniacid' => $this->_uniacid,
                'title' => $data['title']
            ];
        }

        $activityItemsInActivityModel = new ActivityItemsInActivity();
        $activityItemsInActivityModel->saveAll($saveData);

        return $this->success($activity_id);
    }

    public function updateOne()
    {

        if (isset($this->_input['activity_id']))
        {
            $this->_input['id']  = $this->_input['activity_id'];
        }

        $activity_id   = $this->_input['activity_id'] ?? null;

        $m_activity = new ActivityModel();
        $activity = $m_activity->where(['id' => $activity_id])->find();
        if (!$activity)
        {
            return $this->error('活动不存在');
        }

        $input = $this->_input;

        if (isset($input['start_time']) || isset($input['end_time']) || isset($input['sign_start_time'])|| isset($input['sign_end_time']))
        {
            if (($input['sign_start_time'] ?? $activity['sign_start_time'] ) >=$input['start_time'] ?? $activity['start_time'])
            {
                return $this->error('报名开始时间必须小于活动开始时间');
            }

            if (($input['sign_start_time'] ?? $activity['sign_start_time'] ) >= $input['sign_end_time'] ?? $activity['sign_end_time'])
            {
                return $this->error('报名开始时间必须小于活动开始时间');
            }


            if (($input['sign_end_time'] ?? $activity['sign_end_time'] ) > $input['end_time'] ?? $activity['end_time'])
            {
                return $this->error('报名结束时间必须小于活动结束时间');
            }

            if (($input['start_time'] ?? $activity['start_time'] ) >= $input['end_time'] ?? $activity['end_time'])
            {
                return $this->error('活动开始时间必须小于活动结束时间');
            }


        }

        $validate = new ActivityValidate();
        $check = $validate->scene('update')->check($this->_input);
        if ($check == false)
        {
            return $this->error($validate->getError());
        }

        $input = $this->_input;
        $model = new ActivityModel();
        $rst = $model->updateByfilter(['id' => $activity_id], $input);

        $arcitity_item_ids = explode(',', $this->_input['items'] ?? '');

        if ($arcitity_item_ids)
        {

            $items_model = new \app\activity\model\ActivityItem();
            $acticity_items_data = $items_model->getAllByIds($arcitity_item_ids);

            $time = time();
            $saveData = [];
            foreach ($acticity_items_data as $data) {
                $saveData[] = [
                    'create_time' => $time,
                    'update_time' => $time,
                    'activity_id' => $activity_id,
                    'uniacid'     => $this->_uniacid,
                    'title'       => $data['title']
                ];
            }
//            dump($arcitity_item_ids);exit;
            $activityItemsInActivityModel = new ActivityItemsInActivity();
            $activityItemsInActivityModel->destoryByactivityId($activity_id);
            $res = $activityItemsInActivityModel->saveAll($saveData);
        }
        return $this->success($rst);
    }

//  public function getOne()
//  {
//      if (isset($this->_param['activity_id']))
//      {
//          $this->_param['id']  = $this->_param['activity_id'];
//      }
//
//      $validate = new ActivityValidate();
//      $check = $validate->scene('get')->check($this->_param);
//      if ($check == false)
//      {
//          return $this->error($validate->getError());
//      }
//
//      $activity_id = $this->_param['activity_id'] ?? $this->_param['id'] ;
//      $staff_id = $this->_param['staff_id'] ?? null;
//
//
//      $model = new ActivityModel();
//      $data = $model->where(['id' => $activity_id])
//          ->field('id, cover, carousel,title,start_time, end_time, classify_id,
//          sign_limit, detail_images,status,sign_number, text_desc, address,sign_start_time,sign_end_time, longitude,latitude')->find()->toArray();
//
//      $data = transImagesOne($data, ['cover']);
//      $data = transImages($data, ['carousel', 'detail_images'], ';');
//
//      $sign_start_time = $data['sign_start_time'];
//      $sign_end_time = $data['sign_end_time'];
//      $start_time = $data['start_time'];
//      $end_time = $data['end_time'];
//      $sign_limit = $data['sign_limit'];
//      $sign_number = $data['sign_number'];
//      $data['sign_status'] = $this->_getSignStatus($sign_start_time, $sign_end_time, $sign_limit, $sign_number);
//      $data['type'] = $this->_getActivityStatus($start_time, $end_time, $sign_limit, $sign_number);
//      $data['start_time'] = date('Y-m-d H:i', $data['start_time'] );
//      $data['end_time'] = date('Y-m-d H:i', $data['end_time'] );
//      $data['sign_start_time'] = $data['sign_start_time'] != 0 ? date('Y-m-d H:i', $data['sign_start_time'] ) : $data['start_time'];
//      $data['sign_end_time'] = $data['sign_end_time'] != 0 ? date('Y-m-d H:i', $data['sign_end_time'] ) : $data['end_time'];
//
//      $m_user_record = new ActivityUserRecord();
//      $user_records = $m_user_record->where([
//          ['activity_id' ,'=', $activity_id]
//      ])->order('create_time', 'desc')->limit(6)->select()->toArray();
//      $user_ids = array_column($user_records, 'user_id');
//
//      $data['is_signed'] = false;
//      if (in_array($this->_user_id ?? $this->_param['onlyForTestUserId'] ?? null, $user_ids)) {
//          $data['is_signed'] = true;
//      }
//
//      $m_user = new IndexUser();
//      $sign_users = $m_user->where([['id', 'in', $user_ids]])
//          ->field('id as user_id, nickName, avatarUrl ')->select()->toArray();
//      $sign_users = transImagesOne($sign_users, ['avatarUrl']);
//      $data['sign_users'] = $sign_users;
//
//
//      //生成活动二维码
//      $qrData = [
//          'id' => $activity_id,
//          'pid' => $this->_user_id,
//          'staff_id' => $staff_id,
//          'type' => 8
//      ];
//      $src = Cache::get("{$activity_id}-{$this->_user_id}-{$staff_id}-8-activity_qr");
//      if(empty($src)){
//          $datas  = longbingCreateWxCode($this->_uniacid,$qrData,'activity/pages/detai');
//          $data = transImagesOne($data ,['qr_path'] ,$this->_uniacid);
//          $src = $datas['qr_path'];
//          Cache::set("{$activity_id}-{$this->_user_id}-{$staff_id}-8-activity_qr", $datas['qr_path']);
//      }
//
//      $data['activityQr'] = $src;
//      return $this->success($data);
//  }

    public function getOne()
    {
        if (isset($this->_param['activity_id']))
        {
            $this->_param['id']  = $this->_param['activity_id'];
        }

        $validate = new ActivityValidate();
        $check = $validate->scene('get')->check($this->_param);
        if ($check == false)
        {
            return $this->error($validate->getError());
        }

        $activity_id = $this->_param['activity_id'] ?? $this->_param['id'] ;
        $staff_id = $this->_param['staff_id'] ?? null;


        $model = new ActivityModel();
        $data = $model->where(['id' => $activity_id])
            ->field('id, cover, carousel,title,start_time, end_time, classify_id,
            sign_limit, detail_images,content_text,status,sign_number, text_desc, address,sign_start_time,sign_end_time, longitude,latitude')->find()->toArray();

        $data = transImagesOne($data, ['cover']);
        $data = transImages($data, ['carousel', 'detail_images'], ';');

        $sign_start_time = $data['sign_start_time'];
        $sign_end_time = $data['sign_end_time'];
        $start_time = $data['start_time'];
        $end_time = $data['end_time'];
        $sign_limit = $data['sign_limit'];
        $sign_number = $data['sign_number'];
        $data['sign_status'] = $this->_getSignStatus($sign_start_time, $sign_end_time, $sign_limit, $sign_number);
        $data['type'] = $this->_getActivityStatus($start_time, $end_time, $sign_limit, $sign_number);
        $data['start_time'] = date('Y-m-d H:i', $data['start_time'] );
        $data['end_time'] = date('Y-m-d H:i', $data['end_time'] );
        $data['sign_start_time'] = $data['sign_start_time'] != 0 ? date('Y-m-d H:i', $data['sign_start_time'] ) : $data['start_time'];
        $data['sign_end_time'] = $data['sign_end_time'] != 0 ? date('Y-m-d H:i', $data['sign_end_time'] ) : $data['end_time'];

        $m_user_record = new ActivityUserRecord();
        $user_records = $m_user_record->where([
            ['activity_id' ,'=', $activity_id]
        ])->order('create_time', 'desc')->limit(6)->select()->toArray();
        $user_ids = array_column($user_records, 'user_id');

        $data['is_signed'] = false;
        if (in_array($this->_user_id ?? $this->_param['onlyForTestUserId'] ?? null, $user_ids)) {
            $data['is_signed'] = true;
        }

        $m_user = new IndexUser();
        $sign_users = $m_user->where([['id', 'in', $user_ids]])
            ->field('id as user_id, nickName, avatarUrl ')->select()->toArray();
        $sign_users = transImagesOne($sign_users, ['avatarUrl']);
        $data['sign_users'] = $sign_users;


        //生成活动二维码
        $qrData = [
            'id' => $activity_id,
            'pid' => $this->_user_id,
            'staff_id' => $staff_id,
            'type' => 8
        ];
        $src = getCache("{$activity_id}-{$this->_user_id}-{$staff_id}-8-activity_qr", $this->_uniacid);
        if(empty($src)){
            $datas  = longbingCreateWxCode($this->_uniacid,$qrData,'activity/pages/detai');
	    $datas = transImagesOne($datas ,['qr_path'] ,$this->_uniacid);
            $src = $datas['qr_path'];
            setCache("{$activity_id}-{$this->_user_id}-{$staff_id}-8-activity_qr", $datas['qr_path'], 3600, $this->_uniacid);
        }

        $data['activityQr'] = $src;

        $data['content_text'] = getimgsV2($data['content_text']);

        return $this->success($data);
    }

    public function changeStatus()
    {
        if (isset($this->_input['activity_id'])) {
            $this->_input['id']  = $this->_input['activity_id'];
        }

        $validate = new ActivityValidate();
        $check = $validate->scene('updateStatus')->check($this->_input);
        if ($check == false)
        {
            return $this->error($validate->getError());
        }

        $activity_id = $this->_param['activity_id'];
        $input = $this->_input;
        $model = new ActivityModel();
        $rst = $model->updateByfilter(['id' => $activity_id], ['status' => $input['status']]);
        return $this->success($rst);
    }
}